package com.zyz.common.utils;

import com.zyz.common.exception.RedisException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
public class Redis {

    private StringRedisTemplate redisTemplate;

    public Redis(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * redis get 操作
     */
    public String get(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("redis异常，key：{}", key);
            return null;
        }
    }

    /**
     * 判断key是否存在
     */
    public boolean exists(String key) {
        try {
            return key == null ? false : redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("redis haskey error,key: {}", key);
            return false;
        }
    }

    /**
     * set key 操作
     */
    public boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("redis set error,key: {}", key);
            return false;
        }
    }

    /**
     * 设置过期时间单位为秒
     *
     * @param key
     * @param value
     * @param timeout
     * @return
     */
    public boolean setAndExpire(String key, String value, long timeout) {
        if (timeout <= 0) {
            log.error("timeout不合法,timeout: {}", timeout);
            throw new RedisException("timeout不合法");
        }
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
        return true;
    }


    public static String buildKey (String prefix ,String... args) {
        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        for (String arg : args) {
            sb.append(":").append(arg);
        }
        return sb.toString();
    }

}
